<template>
  <div class="app-container">
    <el-card class="box-card" v-loading="loading">
      <div slot="header" class="clearfix">
        <span class="card-title">编辑看板订单</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="small">
        <!-- 协议选择区域 -->
        <el-card class="form-section" shadow="never">
          <div slot="header" class="section-header">
            <i class="el-icon-document"></i>
            <span>协议选择</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="供货协议" prop="frameworkId" required>
                <el-select v-model="form.frameworkId" placeholder="请选择供货协议" filterable clearable
                  @change="handleFrameworkChange" style="width: 100%" :disabled="form.businessStatus > 10">
                  <el-option v-for="item in frameworkList" :key="item.id" :label="item.frameworkCode + ' - ' + item.frameworkName"
                    :value="item.id">
                    <span style="float: left">{{ item.frameworkCode }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.frameworkName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="协议状态">
                <el-tag v-if="selectedFramework" :type="selectedFramework.status === 0 ? 'success' : 'danger'">
                  {{ selectedFramework.status === 0 ? '生效中' : '已失效' }}
                </el-tag>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="selectedFramework">
            <el-col :span="24">
              <div class="framework-info">
                <p><strong>协议名称：</strong>{{ selectedFramework.frameworkName }}</p>
                <p><strong>有效期：</strong>{{ selectedFramework.effectiveDate }} 至 {{ selectedFramework.expiryDate }}</p>
                <p><strong>要货公司：</strong>{{ selectedFramework.receiverCompanyName }}</p>
                <p><strong>发货公司：</strong>{{ selectedFramework.senderCompanyName }}</p>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 基础信息区域 -->
        <el-card class="form-section" shadow="never">
          <div slot="header" class="section-header">
            <i class="el-icon-office-building"></i>
            <span>基础信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="看板编号">
                <el-input v-model="form.kanbanCode" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="业务状态">
                <dict-tag :options="dict.type.yaohuokb_business" :value="form.businessStatus" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="要货公司">
                <el-input v-model="form.receiverCompanyName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货公司">
                <el-input v-model="form.senderCompanyName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="需求部门" prop="receiverDeptName">
                <el-input v-model="form.receiverDeptName" placeholder="请输入需求部门" :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货部门" prop="senderDeptName">
                <el-input v-model="form.senderDeptName" placeholder="请输入发货部门" :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收货仓库" prop="receiverWarehouseName">
                <el-input v-model="form.receiverWarehouseName" placeholder="请输入收货仓库" :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货仓库" prop="senderWarehouseName">
                <el-input v-model="form.senderWarehouseName" placeholder="请输入发货仓库" :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收货联系人" prop="receiverContact">
                <el-input v-model="form.receiverContact" placeholder="请输入收货联系人" :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收货联系电话" prop="receiverPhone">
                <el-input v-model="form.receiverPhone" placeholder="请输入收货联系电话" :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发货联系人" prop="senderContact">
                <el-input v-model="form.senderContact" placeholder="请输入发货联系人" :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货联系电话" prop="senderPhone">
                <el-input v-model="form.senderPhone" placeholder="请输入发货联系电话" :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 物料信息区域 -->
        <el-card class="form-section" shadow="never">
          <div slot="header" class="section-header">
            <i class="el-icon-goods"></i>
            <span>物料信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="物料编码" prop="materialCode" required>
                <el-select v-model="form.materialCode" placeholder="请选择物料" filterable clearable
                  @change="handleMaterialChange" style="width: 100%" :disabled="form.businessStatus > 10">
                  <el-option v-for="item in materialList" :key="item.materialCode" 
                    :label="item.materialCode + ' - ' + item.materialName" :value="item.materialCode">
                    <span style="float: left">{{ item.materialCode }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.materialName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物料名称">
                <el-input v-model="form.materialName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="计量单位">
                <el-input v-model="form.materialUnit" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="包装规格" prop="packageType">
                <el-select v-model="form.packageType" placeholder="请选择包装规格" clearable :disabled="form.businessStatus > 10">
                  <el-option v-for="item in packageOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="包装容量">
                <el-input v-model="form.packageCapacity" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="要货数量" prop="requiredQty" required>
                <el-input-number v-model="form.requiredQty" :min="0" :precision="2" controls-position="right"
                  style="width: 100%" :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="不含税单价">
                <el-input-number v-model="form.unitPrice" :min="0" :precision="4" controls-position="right"
                  style="width: 100%" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="税率(%)">
                <el-input-number v-model="form.taxRate" :min="0" :max="100" :precision="2" controls-position="right"
                  style="width: 100%" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="不含税总价">
                <el-input v-model="totalPriceExcludingTax" readonly>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="含税总价">
                <el-input v-model="totalPriceIncludingTax" readonly>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 时间配置区域 -->
        <el-card class="form-section" shadow="never">
          <div slot="header" class="section-header">
            <i class="el-icon-time"></i>
            <span>时间配置</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="要求到货时间" prop="requiredDeliveryTime" required>
                <el-date-picker v-model="form.requiredDeliveryTime" type="datetime" placeholder="请选择要求到货时间"
                  value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" @change="calculateDeliveryTime" 
                  :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划发货时间" prop="plannedDeliveryTime">
                <el-date-picker v-model="form.plannedDeliveryTime" type="datetime" placeholder="请选择计划发货时间"
                  value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注信息">
                <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息（可选）" 
                  :disabled="form.businessStatus > 10" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 操作记录区域 -->
        <el-card class="form-section" shadow="never" v-if="form.id">
          <div slot="header" class="section-header">
            <i class="el-icon-document-copy"></i>
            <span>操作记录</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="创建人">
                <el-input v-model="form.createBy" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间">
                <el-input v-model="form.createTime" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="form.updateBy">
            <el-col :span="12">
              <el-form-item label="更新人">
                <el-input v-model="form.updateBy" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="更新时间">
                <el-input v-model="form.updateTime" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 操作按钮区域 -->
        <div class="form-footer">
          <el-button @click="goBack">取消</el-button>
          <el-button type="info" @click="saveDraft" :loading="saveLoading" v-if="form.businessStatus === 10">
            保存草稿
          </el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading" v-if="form.businessStatus === 10">
            提交看板
          </el-button>
          <el-button type="success" @click="updateForm" :loading="updateLoading" v-if="form.businessStatus === 10">
            更新保存
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getKanbanOrder, updateKanbanOrder } from '@/api/kanban/kanbanOrder'
import { listSupplyFramework } from '@/api/kanban/supplyFramework'

export default {
  name: 'KanbanOrderEdit',
  dicts: ['yaohuokb_business'],
  data() {
    return {
      // 加载状态
      loading: true,
      // 表单数据
      form: {},
      // 表单验证规则
      rules: {
        frameworkId: [
          { required: true, message: '请选择供货协议', trigger: 'change' }
        ],
        materialCode: [
          { required: true, message: '请选择物料', trigger: 'change' }
        ],
        requiredQty: [
          { required: true, message: '请输入要货数量', trigger: 'blur' }
        ],
        requiredDeliveryTime: [
          { required: true, message: '请选择要求到货时间', trigger: 'change' }
        ],
        receiverPhone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        senderPhone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      // 数据选项
      frameworkList: [],
      materialList: [],
      packageOptions: [
        { label: '标准包装', value: 'standard' },
        { label: '小包装', value: 'small' },
        { label: '大包装', value: 'large' },
        { label: '散装', value: 'bulk' }
      ],
      // 选中的协议
      selectedFramework: null,
      // 加载状态
      saveLoading: false,
      submitLoading: false,
      updateLoading: false
    }
  },
  computed: {
    // 不含税总价
    totalPriceExcludingTax() {
      if (this.form.requiredQty && this.form.unitPrice) {
        return (this.form.requiredQty * this.form.unitPrice).toFixed(2)
      }
      return '0.00'
    },
    // 含税总价
    totalPriceIncludingTax() {
      if (this.form.requiredQty && this.form.unitPrice && this.form.taxRate) {
        const excludingTax = this.form.requiredQty * this.form.unitPrice
        const includingTax = excludingTax * (1 + this.form.taxRate / 100)
        return includingTax.toFixed(2)
      }
      return this.totalPriceExcludingTax
    }
  },
  created() {
    const id = this.$route.params && this.$route.params.id
    if (id) {
      this.getDetail(id)
    }
    this.getFrameworkList()
  },
  methods: {
    /** 获取详情 */
    getDetail(id) {
      this.loading = true
      getKanbanOrder(id).then(response => {
        this.form = response.data
        // 设置选中的协议
        if (this.form.frameworkId) {
          this.handleFrameworkChange(this.form.frameworkId)
        }
        this.loading = false
      })
    },
    /** 获取协议列表 */
    getFrameworkList() {
      listSupplyFramework({ status: 1 }).then(response => {
        this.frameworkList = response.rows || []
      })
    },
    /** 协议选择变化 */
    handleFrameworkChange(frameworkId) {
      if (frameworkId) {
        this.selectedFramework = this.frameworkList.find(item => item.id === frameworkId)
        if (this.selectedFramework) {
          // 自动填充协议相关信息
          this.form.frameworkCode = this.selectedFramework.frameworkCode
          this.form.receiverCompanyId = this.selectedFramework.receiverCompanyId
          this.form.receiverCompanyName = this.selectedFramework.receiverCompanyName
          this.form.senderCompanyId = this.selectedFramework.senderCompanyId
          this.form.senderCompanyName = this.selectedFramework.senderCompanyName
          
          // 获取协议下的物料列表
          this.getMaterialList(frameworkId)
        }
      } else {
        this.selectedFramework = null
        this.materialList = []
      }
    },
    /** 获取物料列表 */
    getMaterialList(frameworkId) {
      // 这里应该调用获取协议物料的接口，暂时使用模拟数据
      this.materialList = [
        {
          materialCode: 'M001',
          materialName: '钢材A型',
          materialUnit: '吨',
          unitPrice: 5000,
          taxRate: 13
        },
        {
          materialCode: 'M002',
          materialName: '钢材B型',
          materialUnit: '吨',
          unitPrice: 5200,
          taxRate: 13
        }
      ]
    },
    /** 物料选择变化 */
    handleMaterialChange(materialCode) {
      if (materialCode) {
        const material = this.materialList.find(item => item.materialCode === materialCode)
        if (material) {
          this.form.materialName = material.materialName
          this.form.materialUnit = material.materialUnit
          this.form.unitPrice = material.unitPrice
          this.form.taxRate = material.taxRate
        }
      } else {
        this.form.materialName = ''
        this.form.materialUnit = ''
        this.form.unitPrice = 0
        this.form.taxRate = 0
      }
    },
    /** 计算发货时间 */
    calculateDeliveryTime() {
      if (this.form.requiredDeliveryTime) {
        // 默认提前2天发货
        const deliveryDate = new Date(this.form.requiredDeliveryTime)
        deliveryDate.setDate(deliveryDate.getDate() - 2)
        this.form.plannedDeliveryTime = this.formatDateTime(deliveryDate)
      }
    },
    /** 格式化日期时间 */
    formatDateTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    /** 保存草稿 */
    saveDraft() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          this.form.businessStatus = 10 // 草稿状态
          updateKanbanOrder(this.form).then(response => {
            this.$modal.msgSuccess('保存草稿成功')
            this.goBack()
          }).finally(() => {
            this.saveLoading = false
          })
        }
      })
    },
    /** 提交表单 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          this.form.businessStatus = 20 // 已创建状态
          updateKanbanOrder(this.form).then(response => {
            this.$modal.msgSuccess('提交看板成功')
            this.goBack()
          }).finally(() => {
            this.submitLoading = false
          })
        }
      })
    },
    /** 更新保存 */
    updateForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.updateLoading = true
          updateKanbanOrder(this.form).then(response => {
            this.$modal.msgSuccess('更新成功')
            this.getDetail(this.form.id)
          }).finally(() => {
            this.updateLoading = false
          })
        }
      })
    },
    /** 返回列表 */
    goBack() {
      this.$router.push('/kanban/kanbanOrder')
    }
  }
}
</script>

<style scoped>
.card-title {
  font-size: 18px;
  font-weight: bold;
}

.form-section {
  margin-bottom: 20px;
}

.section-header {
  font-weight: bold;
  color: #303133;
}

.section-header i {
  margin-right: 8px;
  color: #409EFF;
}

.framework-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 10px;
}

.framework-info p {
  margin: 5px 0;
  color: #606266;
}

.form-footer {
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

.form-footer .el-button {
  margin: 0 10px;
  min-width: 100px;
}
</style>